package com.ruoyi.controller;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.domain.TaskDTO;
import com.ruoyi.remark.domain.BoleRemarkProject;
import com.ruoyi.remark.service.IBoleRemarkProjectService;
import com.ruoyi.service.ProcessService;
import org.camunda.bpm.engine.RepositoryService;
import org.camunda.bpm.engine.RuntimeService;
import org.camunda.bpm.engine.TaskService;
import org.camunda.bpm.engine.task.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
public class BoleRemarkController {

    @Autowired
    private IBoleRemarkProjectService iBoleRemarkProjectService;
    @Autowired
    private RepositoryService repositoryService;
    @Autowired
    private RuntimeService runtimeService;
    @Autowired
    private TaskService taskService;
    @Autowired
    private ProcessService processService;

    protected AjaxResult toAjax(int rows)
    {
        return rows > 0 ? AjaxResult.success() : AjaxResult.error();
    }
    //用户提交   流程引擎出问题时用这个！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！！
//    @PostMapping("/remark/project/user")
//    public AjaxResult addUser(@RequestBody BoleRemarkProject boleRemarkProject)
//    {
//        boleRemarkProject.setUserId(SecurityUtils.getUserId());
//        boleRemarkProject.setWorkload(0L);
//        boleRemarkProject.setStatus("0");
//        return toAjax(boleRemarkProjectService.userAdd(boleRemarkProject));
//    }
    @PostMapping("/remark/project/user")
    public AjaxResult addUser(@RequestBody BoleRemarkProject boleRemarkProject)
    {
        boleRemarkProject.setUserId(SecurityUtils.getUserId());
        boleRemarkProject.setWorkload(0L);
        boleRemarkProject.setStatus("0");

        return toAjax(processService.startProcess(boleRemarkProject, "leaveProcess"));
    }
//    查询待审核的
// 查询待办任务（按负责人）
@GetMapping("/task/list")
public List<TaskDTO> getTasks() {
    List<SysRole> roleList = SecurityUtils.getLoginUser().getUser().getRoles();
    Collection<String> roles = roleList.stream().map(SysRole::getRoleKey).collect(Collectors.toSet());
    // 查询原始任务列表
    List<Task> tasks = taskService.createTaskQuery()
            .taskAssigneeIn(roles.toArray(new String[0]))
            .list();
    return tasks.stream().map(task -> {
        TaskDTO dto = new TaskDTO();
        dto.setId(task.getId());
        dto.setName(task.getName());
        dto.setAssignee(task.getAssignee());
        dto.setCreateTime(task.getCreateTime());

        // 获取流程实例ID（通过任务获取流程实例ID）
        String processInstanceId = task.getProcessInstanceId();

        // 通过流程实例ID获取流程变量（包括dataId）
        Map<String, Object> variables = runtimeService.getVariables(processInstanceId);
        Long dataId = (Long) variables.get("remarkId"); // 提取业务数据ID
        dto.setRemarkId(dataId); // 将dataId存入DTO
//            query.taskAssigneeIn(assignees.toArray(new String[0]))
        return dto;
    }).collect(Collectors.toList());
}
// 完成任务（审批）
//    @PostMapping("/task/complete")
//    public AjaxResult completeTask(@RequestParam("taskId") String taskId,
//                               @RequestParam Map<String, Object> variables) {
//        taskService.complete(taskId, variables);
//        return AjaxResult.success();
//    }
    /**
     * 审核通过标注提交记录
     */
    @PreAuthorize("@ss.hasPermi('remark:project:edit')")
    @Log(title = "标注提交记录", businessType = BusinessType.UPDATE)
    @PutMapping("/task/complete/{taskId}")
    public AjaxResult check(@RequestBody BoleRemarkProject boleRemarkProject,@PathVariable("taskId") String taskId)
    {Map<String, Object> variables=new HashMap<>();
        if (boleRemarkProject.getStatus().equals("4")){
            // 1. 通过任务ID查询任务
            Task task = taskService.createTaskQuery()
                    .taskId(taskId)
                    .singleResult();

            if (task == null) {
                return AjaxResult.error("任务不存在，ID: " + taskId);
            }

            // 2. 获取任务对应的流程实例ID
            String processInstanceId = task.getProcessInstanceId();

            // 3. 删除流程实例
            runtimeService.deleteProcessInstance(
                    processInstanceId,
                    "通过任务ID删除流程实例，任务ID: " + taskId
            );

            iBoleRemarkProjectService.updateBoleRemarkProject(boleRemarkProject);
            return AjaxResult.success();
        }
        boleRemarkProject.setStatus(null);
        taskService.complete(taskId, variables);
        return toAjax(iBoleRemarkProjectService.updateBoleRemarkProject(boleRemarkProject));

    }
    //不通过任务
    @PostMapping("/task/reject/{processInstanceId}")
    public AjaxResult terminateProcessInstance(@PathVariable String processInstanceId,Long remarkId) {
        BoleRemarkProject boleRemarkProject = new BoleRemarkProject();
        boleRemarkProject.setStatus("4");
        iBoleRemarkProjectService.updateBoleRemarkProject(boleRemarkProject);
        runtimeService.deleteProcessInstance(processInstanceId, "手动终止原因");
        return AjaxResult.success();
    }

}
